﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ext.Net;
using Newtonsoft.Json.Linq;

namespace KamLib
{
    public static class ExtUilKeys
    {

        public static UilKey KeyFromJson(string json)
        {
            var d = JSON.Deserialize<Dictionary<string, object>>(json);
            return KeyFromJson(d);
        }

        public static UilKey KeyFromJson(Dictionary<string, object> d)
        {
            var k = new UilKey
            {
                CTID = (string)d.Try("ctid"),
                VTID = (string)d.Try("vtid"),
                VID = (int?)d.Try("vid")
            };

            var id = (JArray)d.Try("id");
            if (id != null)
                k.ID = id.Select(a => a.Select(b => (object)b).ToArray()).ToArray();

            //var lkeys = (JArray)d.Try("links");
            //if (lkeys != null)
            //    k.LinkKeys = lkeys.Select(a => KeyFromJson(((JObject)a).ToDictionary())).ToArray();

            return k;
        }


        public static string ToJson(this UilKey key)
        {
            return String.Concat(
                "{ctid:'", key.CTID, "'",
                key.VTID.isfull() ? ",vtid:'" + key.VTID + "'" : null,
                key.VID != null ? ",vid:'" + key.VID + "'" : null,
                "}"
            );
        }


    }
}
